package com.itheima.exception;

import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result  handleException(Exception e) {
        log.error("服务器发生异常:{}", e);
        return Result.error("服务器发生异常，联系刘宇青");
    }
    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error("异常:{}", e);
        String message = e.getMessage();
        int i = message.indexOf("Duplicate entry");
        String errMsg = message.substring(i);
        String[] s = errMsg.split(" ");
        return Result.error(s[2] + "已存在");
    }
    @ExceptionHandler
    public Result handleBusinessException(RuntimeException r) {
        log.error("程序出错啦", r);
        log.info("================================================");
        System.out.println(r.getMessage());
        log.info("================================================");
        return Result.error(r.getMessage());
    }
}
